import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Card, Avatar, Button, message, Icon, Tooltip, Tag, Row, Col, Spin, Collapse, Modal, Table, Alert } from 'antd';
const Panel = Collapse.Panel;
import styles from './index.less';
import { news, help } from './announcement'
import { RIGHT, COLORS } from '../../constants/index'; // RIGHT: 1 写 6 审 5 发

// const columns = [{
//   title: '等级',
//   dataIndex: 'level',
// }, {
//   title: '近30天写作数',
//   dataIndex: 'write',
// }, {
//   title: '渠道能力数',
//   dataIndex: 'channel',
// }, {
//   title: '近60天阅读数',
//   dataIndex: 'visited60',
// }
// , {
//   title: '近30天尼采平均通过率',
//   dataIndex: 'pass',
// }];
// const level = {
//   level: ['P0','P1','P2','P3','P4','P5','P6','P7'],
//   write: [0,22,33,44,66,88,88,88],
//   channel: [0,1,2,3,3,4,4,4],
//   visited60: [0,2000,5000,30000,100000,200000,1000000,3000000],
//   pass: [0,'40%','60%','70%','80%','90%','90%','90%']
// }
// const tableData = (level => {
//   let arr = [];
//   let keyList = Object.keys(level)
//   for(let i=0; i < 8; i++) {
//     let temp = {key: i}
//     keyList.forEach((key) => {
//       temp[key] = level[key][i]
//     })
//     arr.push(temp)
//   }
//   return arr
// })(level)
@connect(state => ({
  // currentUser: state.user.currentUser,
  // statistics: state.dashboard.statistics,
  // darenInfo: state.user.darenInfo,
}))

export default class Home extends PureComponent {
  // state = { visible: false }

  componentWillMount() {
    // let { dispatch, currentUser: { _id } } = this.props;
    // if (_id) {
    //   dispatch({
    //     type: 'dashboard/fetchDashboardStatistics',
    //     payload: { user_id: _id }
    //   })
    // }
  }
  componentWillReceiveProps(nextProps) {

  }
  componentWillUnmount() {

  }

  // showModal = () => {
  //   this.setState({
  //     visible: true,
  //   });
  // }
  // hideModal = () => {
  //   this.setState({
  //     visible: false,
  //   });
  // }
  /** 数据结构
   * taobao: [{name: ''}, ...{}]
   * nicai: [{_id:{channel_name: ''}}, ...{}]
   */
  // renderItem = (title, num, tips) => (
  //   <Card.Grid  style={{padding: '20px 5px'}}>
  //     <div className={styles['item']} style={{display: 'felx', flexDirection: 'column',textAlign: 'center'}}>
  //       <div className={styles['num']} style={{fontSize: '18px', fontWeight: '800'}}> { num || 0 } </div>
  //       <div className={styles['title']}
  //       style={{whiteSpace: 'nowrap'}}> { title }
  //         {tips && <p style={{display: 'inline'}}>
  //           <Tooltip title={tips} arrowPointAtCenter>
  //             <Icon type="question-circle-o" style={{marginLeft: '5px'}} />
  //           </Tooltip>
  //         </p>}
  //       </div>
  //     </div>
  //   </Card.Grid>
  // )
  // renderLevel = (currLevel, defaultLevel) => {
  //   let levelVnode = [];
  //   let level = 0;
  //   let temp = defaultLevel;
  //   while(temp >= 0) {
  //     let clsName = styles['level-itme'];
  //     let passCls = styles['level-pass'];
  //     let currCls = styles['level-curr'];
  //     if(level < currLevel) {
  //       clsName = passCls
  //     } else if (level === currLevel) {
  //       clsName = currCls
  //     }
  //     if (level === defaultLevel) {
  //       levelVnode.push(
  //         <span key={level} className={styles['level-itme']}
  //         style={{ background: level === currLevel ? 'red' : '#fff', color: level === currLevel ? '#fff' : '#9e9e9e'}}>
  //          P{ level } </span>
  //       )
  //     } else {
  //       levelVnode.push(
  //         <span key={level}>
  //           <span className={styles['level-itme']} style={{
  //              background: level === currLevel ? 'red' : '#fff',
  //              border: level < currLevel ? '1px solid red' : level === currLevel ? 'none' : '1px solid #9e9e9e',
  //              color: level < currLevel ? 'red' : level === currLevel ? '#fff' : '#9e9e9e'
  //             }}
  //           > P{ level } </span>
  //           <p className={styles['line']} style={{background: level < currLevel ? 'red': '#9e9e9e'}}></p>
  //         </span>
  //       )
  //     }
  //     level++;
  //     temp--;
  //   }
  //   return levelVnode;
  // }
  renderNews = news => {
    let newsVnode = [];
    const Header = (title, idx, download, time) => (
      <div className={styles['item-title']} style={{display: 'flex',
        justifyContent: 'space-between'}}>
        <h3>
          {idx === 0 && <Tag color="#f50" style={{cursor: 'default'}}>New</Tag>}
          {time && <p className={styles['time']} style={{display: 'inline-block'}}>{`[${time}]`}</p>}
          {title}
        </h3>
        {download &&
          <div className={styles['download']}>
            <a href={download} target="_blank" style={{marginRight: 40}} >下载chrome</a>
            <a href={download} target="_blank">下载插件</a>
          </div>
        }
      </div>
    )
    news.forEach((item, id) => {
      let { children, title, time, download } = item;
      newsVnode.push(
          <div key={`newsVnode${id}`}>
            {Header(title, id, download, time)}
            <ul className={styles['children-list']} style={{padding: '8px 0'}}>
              {children && children.map((it, idx) => <li className={styles['text']} key={idx}>{it.title}</li>)}
              {id === 0 &&<div style={{color: 'red', marginTop: '2px'}}>注意：使用新功能前请重启浏览器 或者 刷新尼采平台页面和标签栏中第一个淘宝页面哦～</div>}
            </ul>
          </div>
      )
    });
    return newsVnode;
  }
  renderHelpDoc = help => {
    let helpVnode = [];
    let no = ['一', '二', '三', '四']
    help.forEach((item, idx) => {
      let { children, title } = item;
      helpVnode.push(
        <li key={idx}>
          <span className={styles['item-title']}>
            {no[idx]}、{title}
          </span>
          {children && <ul className={styles['children-list']}>
            {children.map((it, id) => <li key={id}>
              <a className={styles['text']} href={it.download} target="_blank">{it.title}</a>
              </li>)}
          </ul>}
        </li>
      )
    })
    return helpVnode
  }
  // renderLable = channelAmont => {
  //   let lableVnode = [];
  //   let cid = 0;
  //   channelAmont.forEach((item, id) =>{
  //     let colorId = (cid + 1) % COLORS.length;
  //     cid++;
  //     item._id && lableVnode.push(<Tag key={id} color={COLORS[colorId]} style={{marginBottom: '5px',cursor: 'default'}}>{item._id}</Tag>)
  //   })
  //   return lableVnode;
  // }

  render() {
    // let isLoad = true;
    // let { rights, avatar, nickname, writer_level } = this.props.currentUser;

    // let hasWrite = rights && (rights.indexOf(RIGHT.writer) >= 0);
    // let hasReview = rights && (rights.indexOf(RIGHT.approver) >= 0);
    // let hasPublish = rights && (rights.indexOf(RIGHT.daren) >= 0);

    // let amountApprove = 0;
    // let amountPublish = 0;
    // let amountWrite = 0;
    // let nicaiPassedRate = 0;
    // let channel = [];
    // let sumReadCnt = 0;
    // let sixtysummary = 0;
    // let channelAmont = [];
    // let takerWrite = 0;

    // if(JSON.stringify(this.props.statistics) !== '{}') {
    //   isLoad = false;
    //   takerWrite = this.props.statistics.takerWrite;
    //   amountApprove = this.props.statistics.amountApprove;
    //   amountPublish = this.props.statistics.amountPublish;
    //   amountWrite = this.props.statistics.amountWrite;
    //   nicaiPassedRate = this.props.statistics.nicaiPassedRate.toFixed(4);

    //   if(this.props.statistics.summary.length) {
    //     sumReadCnt = this.props.statistics.summary[0].sumReadCnt;
    //   }
    //   if(this.props.statistics.sixtysummary.length) {
    //     sixtysummary = this.props.statistics.sixtysummary[0].sumReadCnt;
    //   }
    //   if(this.props.statistics.channelAmont.length) {
    //     channelAmont = this.props.statistics.channelAmont;
    //   }
    // }
    // if(nicaiPassedRate !== 0) {
    //   nicaiPassedRate = `${(nicaiPassedRate * 100).toFixed(2)}%`
    // }
    return (
      <div className={styles['nr-home']}>
      {/* {hasWrite &&<Spin spinning={isLoad}>
        <Card bodyStyle={{padding: '30px 20px'}}>
          <div className={styles['user-avatar']}>
            <Avatar shape="square" size="large" src={avatar} />
          </div>
          <div className={styles['user-info']} >
            <div className={styles['title']}> {nickname} </div>
            <div className={styles['level']}>
              {this.renderLevel(writer_level, 7)}
              <span style={{marginLeft: '15px', cursor: 'pointer', color: '#1890ff'}}
                onClick={this.showModal}
              >写作等级<Tooltip title='点击查看明细' arrowPointAtCenter>
              <Icon type="question-circle-o" style={{marginLeft: '5px'}} />
            </Tooltip></span>
            </div>
            <div className="lable" style={{marginTop: '20px', display: 'inline-block'}}>
              {this.renderLable(channelAmont)}
            </div>
          </div>
        </Card>
      </Spin>} */}
      {/* {(hasWrite) && <Spin spinning={isLoad}>
        <Card bodyStyle={{padding: '30px 20px'}} className={styles['card']}>
          <div className={styles['notice']}>
            <div className={styles['item-list']}>
              {this.renderItem('总阅读数', sumReadCnt)}
              {this.renderItem('总写作数', takerWrite)}
              {this.renderItem('近60天总阅读数', sixtysummary)}
              {this.renderItem('近30天写作数', amountWrite)}
              {this.renderItem('渠道能力数', channelAmont.length, '尼采通过五篇的渠道')}
              {this.renderItem('尼采通过率', nicaiPassedRate, '文章(已通过)的通过率的平均值,  ( Σ(1 / (稿子不通过次数 + 1))  / 稿子数 )')}
            </div>
          </div>
        </Card>
        </Spin>} */}
        <Row type="flex" justify="space-between" align="top" className={styles['nicai-info']}>
          <MyCol span={17} title='平台公告'>
            {/* <Collapse bordered={false} defaultActiveKey={['0']}> */}
              {this.renderNews(news)}
            {/* </Collapse> */}
          </MyCol>
          <MyCol span={6} title='常见问题'>
           {this.renderHelpDoc(help)}
          </MyCol>
        </Row>
        {/* <Modal
          title="写作等级"
          onOk={this.hideModal}
          onCancel={this.hideModal}
          visible={this.state.visible}
          pagination={false}
          size='small'
          footer={[
            <Button key="back" onClick={this.hideModal}>知道了</Button>,
          ]}
          width={900}
          bodyStyle={{
            height: '400px',
            width: '900px',
            overflow: 'auto'
          }}
        >
        <Alert message="此功能仅针对小编进行考评管理" type="info" showIcon />
        <Card bodyStyle={{padding: '30px 20px'}} className={styles['card']} bordered={false}>
          <div className={styles['notice']}>
            <div className={styles['item-list']}
            style={{display:'flex', flexDirection: 'row'}}>
              {this.renderItem('近30天写作数', amountWrite)}
              {this.renderItem('渠道能力数', channelAmont.length, '尼采通过五篇的渠道')}
              {this.renderItem('近60天总阅读数', sixtysummary)}
              {this.renderItem('尼采通过率', nicaiPassedRate, '文章(已通过)的通过率的平均值,  ( Σ(1 / (稿子不通过次数 + 1))  / 稿子数 )')}
            </div>
          </div>
          </Card>
          <Card bordered={false}>
          <Table
            columns={columns}
            dataSource={tableData}
            bordered
            title={() => '小编动态等级评估标准'}
          />
          </Card>
        </Modal> */}
      </div>
    );
  }
}

class MyCol extends PureComponent {
  render() {
    let { span, title } = this.props
    return (<Col span={span}>
      <Card bodyStyle={{padding: '10px 20px'}}>
        <div className={styles['nav-title']}> { title }</div>
        <ol className={styles['container']}>
          {this.props.children}
        </ol>
      </Card>
    </Col>)
  }
}
